// import { HomePath } from '@/common/constants'
import { action, makeObservable, observable } from 'mobx'
import { db } from '@/utils/db'
import { HomePath } from '@/common/constants'

export interface ITag {
  // name: string
  path: string
  // fullPath: string
  title: string
}
// const fixed = { title: '公告板', path: HomePath }

class Tag {
  constructor() {
    makeObservable(this)
  }

  @observable opened = []

  @observable tagList = []

  // 设置菜单显示状态
  @action setOpened = (list: any) => {
    this.opened = list
  }

  // 设置菜单显示状态
  @action setTagList = (list: any) => {
    this.tagList = list
  }

  @action save(value: any) {
    db.dbSet({ dbName: 'user', path: 'tags.opened', value })
  }

  @action addTag(tag: any) {
    const hasTag = this.tagList.some((item: any) => item.key === tag.key)
    const newTag = hasTag ? this.tagList : [...this.tagList, tag]

    this.setTagList(newTag)
    this.save(newTag)
  }

  @action deleteTag(key: string) {
    const newTag = [...this.tagList.filter((item: any) => item.key !== key)]

    this.setTagList(newTag)
    this.save(newTag)
  }

  @action emptyTag() {
    const newTag = [...this.tagList.filter((item: any) => item.key === HomePath)]
    this.setTagList(newTag)
    this.save(newTag)
  }

  @action closeLeftTags(path: string, index: number) {
    const curIndex = index ?? this.tagList.findIndex((item: any) => item.key === path)
    const newTag = this.tagList.filter((item: any, i: number) => i >= curIndex)

    this.setTagList(newTag)
    this.save(newTag)
  }

  @action closeRightTags(path: string, index: number) {
    const curIndex = index ?? this.tagList.findIndex((item: any) => item.key === path)
    const newTag = this.tagList.filter((item: any, i: number) => i <= curIndex)

    this.setTagList(newTag)
    this.save(newTag)
  }

  @action closeOtherTag(key: string) {
    const newTag = [...this.tagList.filter((item: any) => item.key === HomePath || item.key === key)]

    this.setTagList(newTag)
    this.save(newTag)
  }
}

export default new Tag()
